package com.litchi.tutor.common.config.upload;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * @author hoby
 * @since 2021-08-19
 */
@Configuration
public class UploadConfiguration {

    @Value("${tempPath:/data/springboot-demo/temp/}")
    private String tempPath;

    @Value("${multipart.max-file-size:10MB}")
    private String maxfilesize;

    @Value("${multipart.max-request-size:15MB}")
    private String maxrequestsize;

    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
        multipartResolver.setResolveLazily(true);
        return multipartResolver;
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        File path = new File(tempPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(tempPath);
        factory.setMaxFileSize(DataSize.parse(maxfilesize));
        factory.setMaxRequestSize(DataSize.parse(maxrequestsize));
        return factory.createMultipartConfig();
    }
}
